<template lang="pug">
.cp-product-query-table
  el-dialog.query-pop(
    :title="title",
    :visible="visible",
    @close="closeDialog",
    :close-on-click-modal="!isEdit",
    width="60%")
    .table-title
      div 查询条件列表
      div.right-btn(v-if="isEdit")
        el-tooltip(content="新建组合")
          i.icon-act.el-icon-tickets(@click="createSet")
        el-tooltip(content="新建条件")
          i.icon-act.el-icon-document(@click="createQuery")
        el-tooltip(content="编辑")
          i.icon-act.el-icon-edit(@click="editQuery")
        el-tooltip(content="删除")
          i.icon-act.el-icon-delete(@click="deleteQuery")
    el-table.query-pop-table(
      ref="table",
      :data="tableData",
      highlight-current-row,
      height="398px",
      @row-click="handleRowClick",
      v-loading="loadingData",
      stripe,
      border)
      el-table-column(show-overflow-tooltip, prop="type", label="节点", min-width="200px")
        template(slot-scope="scope")
          div.type-text(:style="calcWidth(scope.row)") {{scope.row.type | compare-list(typeSelect)}}
      el-table-column(show-overflow-tooltip, label="条件属性")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.type === 'type1'") {{scope.row.conAttr | compare-list(conAttrSelect)}}
          el-select(v-show="scope.row.canEdit && scope.row.type === 'type1'", v-model="scope.row.conAttr")
            el-option(
              v-for="(item, index) in conAttrSelect",
              :key="index", :label="item.name",
              :value="item.value")
      el-table-column(show-overflow-tooltip, label="条件关系")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.type === 'type1'") {{scope.row.conAffect | compare-list(conAffectSelect)}}
          el-select(v-show="scope.row.canEdit && scope.row.type === 'type1'", v-model="scope.row.conAffect")
            el-option(
              v-for="(item, index) in conAffectSelect",
              :key="index", :label="item.name",
              :value="item.value")
      el-table-column(show-overflow-tooltip, label="条件值")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.type === 'type1'") {{scope.row.conValue}}
          el-input(v-show="scope.row.canEdit && scope.row.type === 'type1'", v-model="scope.row.conValue")
      el-table-column(show-overflow-tooltip, label="节点关系")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.nodeAffect | compare-list(nodeAffectSelect)}}
          el-select(v-show="scope.row.canEdit", v-model="scope.row.nodeAffect")
            el-option(
              v-for="(item, index) in nodeAffectSelect",
              :key="index", :label="item.name",
              :value="item.value")
      el-table-column(label="操作", min-width="48px", fixed="right", v-if="isEdit")
        template(slot-scope="scope")
          div(v-show="scope.row.canEdit")
            el-tooltip(content="保存")
              i.icon-act.el-icon-check(@click="saveEditItem(scope.$index, scope.row)")
            el-tooltip(content="取消")
              i.icon-act.el-icon-close(@click="cancelEditItem(scope.$index, scope.row)")
    .dialog-footer(slot="footer")
      el-button(type="primary", plain, @click="closeDialog") 取消
      el-button(type="primary", @click="saveTableData", v-if="isEdit", :disabled="saving") 保存
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  name: 'checkoutform',
  props: {
    title: String,
    visible: Boolean,
    isEdit: Boolean,
    parentData: Array
  },
  data() {
    return {
      // 新建时初始数据
      tableData: this.parentData,
      loadingData: false,
      // 当前选择
      currentRow: null,
      saving: false,
      submitting: false,
      // 下拉框选项
      typeSelect: [
        { name: '组合', value: 'type0' },
        { name: '条件', value: 'type1' }
      ],
      conAttrSelect: [
        { name: '标签', value: '0' },
        { name: '创建人', value: '1' },
        { name: '指派人', value: '2' },
        { name: '创建时间', value: '3' },
        { name: '类型', value: '4' },
        { name: '状态', value: '5' },
        { name: '标题', value: '6' },
        { name: '描述', value: '7' },
        { name: '模块', value: '8' },
        { name: '标签', value: '9' }
      ],
      conAffectSelect: [
        { name: '=', value: '0' },
        { name: '>', value: '1' },
        { name: '>=', value: '2' },
        { name: '<', value: '3' },
        { name: '<=', value: '4' },
        { name: '<>', value: '5' },
        { name: 'LIKE', value: '6' },
        { name: '[]', value: '7' }
      ],
      nodeAffectSelect: [
        { name: 'AND', value: '0' },
        { name: 'OR', value: '1' }
      ]
    };
  },
  computed: {
    ...mapGetters({})
  },
  watch: {
    parentData(newData, oldData) {
      if (newData !== oldData) {
        this.tableData = newData;
        this.dataCache = newData ? newData.slice() : [];
      }
    }
  },
  created() {
    // 缓存编辑表格数据
    this.dataCache = this.parentData ? this.parentData.slice() : [];
  },
  methods: {
    // 关闭、取消
    closeDialog() {
      this.$emit('close');
    },
    // 计算名称偏移
    calcWidth(data) {
      const len = (data.level) * 18;
      return {
        paddingLeft: `${len}px`
      };
    },
    // 监听选择行
    handleRowClick(row) {
      if (this.currentRow && this.currentRow.key === row.key) {
        // 取消选中
        this.currentRow = null;
        this.$refs.table.setCurrentRow();
      } else {
        this.currentRow = row;
      }
    },
    // 新建组合
    createSet() {
      if (this.currentRow) {
        if (this.currentRow.type === 'type1') return;
        const level = this.currentRow.level + 1;
        let key = '';
        const len = this.currentRow.children || 0;
        if (len > 0) {
          key = `${this.currentRow.key}-${this.currentRow.children + 1}`;
        } else {
          key = `${this.currentRow.key}-1`;
        }
        // 获取选择行的索引
        const i = this.tableData.findIndex(item => item.key === this.currentRow.key);
        // 前一行的索引
        const index = i + this.currentRow.children;
        this.tableData.splice((index + 1), 0, { key, level, parent: this.currentRow.key, children: 0, type: 'type0', canEdit: true });
        this.dataCache.splice((index + 1), 0, { key, level, parent: this.currentRow.key, children: 0, type: 'type0', canEdit: true, fromAdd: true });
        this.currentRow.children += 1;
      } else {
        // 已有一级节点数量
        let key = 0;
        this.tableData.forEach((item) => {
          if (item.level == 1) {
            key += 1;
          }
        });
        this.tableData.push({ key: `${key + 1}`, level: 1, parent: null, children: 0, type: 'type0', canEdit: true });
        this.dataCache.push({ key: `${key + 1}`, level: 1, parent: null, children: 0, type: 'type0', canEdit: true, fromAdd: true });
      }
    },
    // 新建条件
    createQuery() {
      if (this.currentRow) {
        if (this.currentRow.type === 'type1') return;
        const level = this.currentRow.level + 1;
        let key = '';
        const len = this.currentRow.children || 0;
        if (len > 0) {
          key = `${this.currentRow.key}-${this.currentRow.children + 1}`;
        } else {
          key = `${this.currentRow.key}-1`;
        }
        // 获取选择行的索引
        const i = this.tableData.findIndex(item => item.key === this.currentRow.key);
        // 前一行的索引
        const index = i + this.currentRow.children;
        this.tableData.splice((index + 1), 0, { key, level, parent: this.currentRow.key, type: 'type1', canEdit: true });
        this.dataCache.splice((index + 1), 0, { key, level, parent: this.currentRow.key, type: 'type1', canEdit: true, fromAdd: true });
        this.currentRow.children += 1;
      } else {
        // 已有一级节点数量
        let key = 0;
        this.tableData.forEach((item) => {
          if (item.level == 1) {
            key += 1;
          }
        });
        this.tableData.push({ key: `${key + 1}`, level: 1, parent: null, type: 'type1', canEdit: true });
        this.dataCache.push({ key: `${key + 1}`, level: 1, parent: null, type: 'type1', canEdit: true, fromAdd: true });
      }
    },
    // 编辑条件
    editQuery() {
      if (!this.currentRow) {
        this.$message.info('请先选择节点');
        return;
      }
      // 获取选择行的索引
      const index = this.tableData.findIndex(item => item.key === this.currentRow.key);
      this.dataCache[index] = Object.assign({}, this.tableData[index]);
      this.$set(this.tableData[index], 'canEdit', true);
    },
    // 删除条件
    deleteQuery() {
      if (!this.currentRow) {
        this.$message.info('请先选择节点');
        return;
      }
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const key = this.currentRow.key;
        const len = this.currentRow.key.length;
        const arr = this.tableData.filter((item) => {
          if (item.key.substring(0, len) === key) {
            return false;
          }
          return true;
        });
        this.tableData = arr;
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },
    /* ****** 表格操作  ****** */
    saveEditItem(index) {
      this.tableData[index].canEdit = false;
    },
    cancelEditItem(index) {
      const cache = Object.assign({}, this.dataCache[index], { canEdit: false });
      if (cache.fromAdd) {
        this.tableData.splice(index, 1);
        this.dataCache.splice(index, 1);
      } else {
        this.tableData.splice(index, 1, cache);
        this.tableData[index].canEdit = false;
      }
    },
    // 校验
    validTable() {
      let canSave = true;
      if (!this.tableData || !this.tableData.length) {
        this.$message.error('列表不能为空');
        canSave = false;
        return false;
      }
      this.tableData.forEach((item) => {
        if (item.canEdit) {
          this.$message.error('请先确认列表项');
          canSave = false;
          return false;
        }
      });
      return canSave;
    },
    // 保存
    saveTableData() {
      if (this.saving) {
        return false;
      }
      this.saving = true;
      if (!this.validTable()) {
        this.saving = false;
        return false;
      }
      /* const params = {
        ...this.tableData,
      }; */
      setTimeout(() => {
        this.closeDialog();
        this.$message({ message: '保存成功', type: 'success' });
        this.saving = false;
      }, 500);
    }
  }
};
</script>

<style lang="sass">
.cp-product-query-table
  .el-table
    th, td
      text-align: center
  .query-pop
    &::-webkit-scrollbar
      display: none
    .el-dialog
      margin-top: 5vh!important
    .el-dialog__body
      padding: 4px 20px
    .el-dialog__footer
      text-align: center
      padding-top: 0
      .el-button
        width: 80px
  .table-title
    position: relative
    line-height: 40px
    font-size: 16px
    .right-btn
      position: absolute
      top: 0
      right: 8px
      line-height: 40px
      .icon-act
        font-size: 18px
  .query-pop-table
    .el-table__body tr.current-row>td
      background-color: #add0f5
    .type-text
      text-align: left
    .icon-act
      font-size: 16px
      font-weight: 500
      padding: 4px
      cursor: pointer
      &:hover
        color: #5D9BFB
  .dialog-footer
    padding-top: 15px
    text-align: center
</style>
